import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { login, logout, getUserInfo } from '@/api/auth/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref((() => {
    const savedUserInfo = Cookies.get('userInfo')
    try {
      return savedUserInfo ? JSON.parse(savedUserInfo) : null
    } catch (error) {
      console.error('解析用户信息失败:', error)
      return null
    }
  })())
  const permissions = ref([])

  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const isStudent = computed(() => userInfo.value?.role === 'student')

  // 登录
  const loginAction = async (loginForm) => {
    try {
      console.log('开始登录，请求参数:', loginForm)
      const response = await login(loginForm)
      console.log('登录API完整响应:', response)
      console.log('登录API响应数据:', response.data)
      console.log('响应数据结构:', JSON.stringify(response.data, null, 2))
      console.log('message字段:', response.data?.message)
      console.log('data字段:', response.data?.data)
      console.log('条件判断结果:', response.data?.message === '成功', response.data?.data === '登录成功')
      
      // 处理新的登录响应格式
      // 现在API返回: {code: 200, message: '成功', data: {token: 'xxx', userInfo: {...}}}
      
      if (response.code === 200 && response.message === '成功' && response.data) {
        const loginData = response.data
        
        // 检查是否包含token和userInfo
        if (loginData.token && loginData.userInfo) {
          console.log('登录成功，获取到token和用户信息')
          
          const userData = loginData.userInfo
          
          // 构建用户信息对象
          const userInfoData = {
            id: userData.userId,
            username: userData.username,
            name: userData.name || userData.username, // 添加name字段，优先使用后端返回的name，否则使用username
            email: userData.email,
            role: userData.roles?.[0] || 'student', // 使用后端返回的第一个角色
            roles: userData.roles || ['student']
          }
          
          // 保存到cookie和状态
          Cookies.set('token', loginData.token, { expires: 7 })
          Cookies.set('userInfo', JSON.stringify(userInfoData), { expires: 7 })
          
          token.value = loginData.token
          userInfo.value = userInfoData
          
          console.log('设置的用户信息:', userInfo.value)
          console.log('用户角色:', userInfo.value?.role)
          
          return { success: true, data: response.data }
        } else {
          throw new Error('登录响应缺少token或用户信息')
        }
      } else {
        console.error('登录响应格式不匹配，期望: code=200 && message="成功" && data包含token和userInfo')
        console.error('实际收到:', { code: response.code, message: response.message, data: response.data })
        throw new Error('登录响应格式异常')
      }
    } catch (error) {
      console.error('登录错误详情:', error)
      if (error.code === 'ECONNREFUSED' || (error.message && error.message.includes('Network Error'))) {
        return { success: false, message: '无法连接到服务器，请检查后端服务是否启动' }
      }
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      // 只有在有token的情况下才调用logout API
      if (token.value) {
        await logout()
      }
    } catch (error) {
      // 静默处理登出API错误，不在控制台显示
      // console.error('登出请求失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      Cookies.remove('token')
      Cookies.remove('userInfo')
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      const userData = response.data
      
      // 处理用户信息，确保角色格式正确
      const processedUserInfo = {
        ...userData,
        name: userData.name || userData.username, // 添加name字段，优先使用后端返回的name，否则使用username
        role: userData.roles?.[0] || userData.role || 'student', // 优先使用roles数组的第一个元素
        roles: userData.roles || (userData.role ? [userData.role] : ['student'])
      }
      
      userInfo.value = processedUserInfo
      permissions.value = userData.permissions || []
      
      // 同时更新cookie中的用户信息
      Cookies.set('userInfo', JSON.stringify(processedUserInfo), { expires: 7 })
      
      console.log('getUserInfo处理后的用户信息:', processedUserInfo)
      return processedUserInfo
    } catch (error) {
      // token失效，静默清除登录状态（不调用logout API）
      token.value = ''
      userInfo.value = null
      permissions.value = []
      Cookies.remove('token')
      Cookies.remove('userInfo')
      throw error
    }
  }

  // 初始化用户信息
  const initUser = async () => {
    if (token.value) {
      // 如果已经有用户信息（从cookie恢复），则不需要重新获取
      if (userInfo.value) {
        // console.log('用户信息已存在，跳过API调用:', userInfo.value)
        return
      }
      
      try {
        console.log('从API获取用户信息')
        await getUserInfoAction()
      } catch (error) {
        console.log('获取用户信息失败，清除登录状态')
        // token失效，清除登录状态
        token.value = ''
        userInfo.value = null
        permissions.value = []
        Cookies.remove('token')
        Cookies.remove('userInfo')
        throw error
      }
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  return {
    token,
    userInfo,
    permissions,
    isAuthenticated,
    isAdmin,
    isStudent,
    loginAction,
    logoutAction,
    getUserInfoAction,
    initUser,
    hasPermission
  }
})